package com.evil.application.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.evil.application.pojo.dto.group.ApplicationGroupReqDTO;
import com.evil.application.pojo.entity.ApplicationGroup;
import com.evil.common.application.util.ApplicationRedisKeyUtil;
import com.evil.common.core.constant.RedisConstant;
import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.core.util.CacheMapperUtil;
import com.evil.common.core.util.StreamUtil;
import org.apache.ibatis.annotations.Param;

import java.util.*;

/**
 * 应用组表
 *
 * @author liyang
 * @date 2023-02-15 16:03
 */
public interface ApplicationGroupMapper extends BaseMapper<ApplicationGroup> {

    Optional<ApplicationGroup> isExistById(Long id);

    default Optional<ApplicationGroup> isExistById_Cache(Long id) {
        return CacheMapperUtil.cacheById(
                id,
                ApplicationGroup.class,
                this::findById,
                ApplicationRedisKeyUtil::requestUuidPackageKey,
                RedisConstant.REQUEST_UUID_EXPIRE_IN_SECOND
        );
    }

    default ApplicationGroup findById(Long id) {
        return this.isExistById(id).orElseThrow(() -> new BusinessException(RCodeEnum.APPLICATION_GROUP_NOT_EXIST));
    }

    default ApplicationGroup findById_Cache(Long id) {
        return this.isExistById_Cache(id).orElseThrow(() -> new BusinessException(RCodeEnum.APPLICATION_GROUP_NOT_EXIST));
    }

    List<ApplicationGroup> findByIds(@Param("ids") Collection<Long> ids, @Param("filterDeleted") boolean filterDeleted);

    default List<ApplicationGroup> findByIds_Cache(Collection<Long> ids, boolean filterDeleted) {
        return CacheMapperUtil.cacheByIds(
                ids,
                filterDeleted,
                ApplicationGroup.class,
                this::findByIds,
                ApplicationGroup::getApplicationGroupId,
                ApplicationGroup::getIsDeleted,
                Comparator.comparing(ApplicationGroup::getSort),
                ApplicationRedisKeyUtil::requestUuidGroupKeyMap,
                RedisConstant.REQUEST_UUID_EXPIRE_IN_SECOND
        );
    }

    List<ApplicationGroup> findByApplicationGroupReqDTO(ApplicationGroupReqDTO applicationGroupReqDTO);

    List<ApplicationGroup> findByEnterpriseId(Long enterpriseId);

    default Map<Long, ApplicationGroup> findMapByIds(Collection<Long> ids, boolean filterDeleted) {
        return StreamUtil.toMapK(this.findByIds(ids, filterDeleted), ApplicationGroup::getApplicationGroupId);
    }
}